package org.scboy.dbms.service.imp;

import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.dbms.dao.BaseRequestValidConfigDao;
import org.scboy.dbms.dao.BaseValidClassDao;
import org.scboy.dbms.service.RequestValidConfigService;
import org.scboy.utils.entitys.coobi.Model;
import org.scboy.utils.entitys.coobi.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.lang.UUID;

@Service
public class RequestValidConfigServiceImpl implements RequestValidConfigService {

	@Autowired
	EntityFactory factory;
	
	/**
	 * 分页查询验证规则配置
	 * @param params
	 * @return
	 */
	public Page page(Model params){
		BaseRequestValidConfigDao dao=factory.getDao(BaseRequestValidConfigDao.class);
		return dao.page(params);
	}
	
	/**
	 * 获取验证规则配置
	 * @param id
	 * @return
	 */
	public Model get(String id){
		BaseRequestValidConfigDao dao=factory.getDao(BaseRequestValidConfigDao.class);
		return dao.get(Model.create().add("id", id));
	}
	
	/**
	 * 新增验证规则配置
	 * @param model
	 * @return
	 */
	public boolean add(Model model){
		
		BaseValidClassDao classDao=factory.getDao(BaseValidClassDao.class);
		BaseRequestValidConfigDao dao=factory.getDao(BaseRequestValidConfigDao.class);
		
		Long count=dao.count(
				Model.create().add("validClass", model.getString("validClass"))
				.add("rvpid", model.getString("rvpid")));
		if(count>0){
			return false;
		}
		Model vc=classDao.get(Model.create().add("className", model.getString("validClass")));
		model.add("validName", vc.getString("validName"));
		model.add("id", UUID.randomUUID().toString());
		int result=dao.insert(model);
		if(result>0){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 更新验证规则配置信息
	 * @param model
	 * @return
	 */
	public boolean update(Model model){
		BaseValidClassDao classDao=factory.getDao(BaseValidClassDao.class);
		BaseRequestValidConfigDao dao=factory.getDao(BaseRequestValidConfigDao.class);
		Model oldModel=get(model.getString("id"));
		Long count=dao.count(
				Model.create().add("validClass", model.getString("validClass"))
				.add("rvpid", oldModel.getString("rvpid"))
				.NE("id", model.getString("id")));
		if(count>0){
			return false;
		}
		Model vc=classDao.get(Model.create().add("className", model.getString("validClass")));
		model.add("validName", vc.getString("validName"));
		int result=dao.update(model,Model.create().add("id", model.getString("id")));
		if(result>0){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 删除验证规则配置信息
	 * @param id
	 * @return
	 */
	@Transactional
	public boolean delete(String id){
		BaseRequestValidConfigDao dao=factory.getDao(BaseRequestValidConfigDao.class);
		int count=dao.delete(Model.create().add("id", id));
		if(count>0) {
			return true;
		}else {
			return false;
		}
	}
}
